package com.youyicloud.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ObjectUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;  

public class QRCodeUtil {  

	/**
	 * 将字符串信息封装进二维码中
	 * @param encodeStr
	 * @return
	 */
	public static String getBase64ImgStr(String encodeStr) {
		String encodeString = Base64.encodeBase64String(encodeStr.getBytes());
        ByteArrayOutputStream out = QRCode.from(encodeString).to(ImageType.PNG).stream();
        String baseimg = Base64.encodeBase64String(out.toByteArray());
        return baseimg;
	}
	
	/**
	 * 生成二维码图片
	 * @param content  内容字符串 testStr
	 * @param filePath 文件路径 D:\\
	 * @param fileName 文件名 test.png
	 * @param picType 文件类型 png jpg
	 * @return
	 */
	 public static boolean genQrCode(String content,String filePath,String fileName,String picType){  
	        int width = 200; // 图像宽度  
	        int height = 200; // 图像高度
	        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
	        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
	        BitMatrix bitMatrix;
			try {
				bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);
				Path path = FileSystems.getDefault().getPath(filePath, fileName);
				bitMatrix = deleteWhite(bitMatrix);//删除白边
				MatrixToImageWriter.writeToPath(bitMatrix, picType, path);// 输出图像
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("生成二维码失败....");
				return false;
			}// 生成矩阵  
	        return true;
	    }  
	
	 /**
     * 删除白边
     * */
    public static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }
    public static void main(String[] args) {  
        /*UserInfo userInfo = new UserInfo();
        userInfo.setUserId(1);
        userInfo.setUserName("wuxiaofan");
        userInfo.setBalance(222);
        System.out.println(JSONObject.toJSONString(userInfo));
        String encodeString = Base64.encodeBase64String(JSONObject.toJSONString(userInfo).getBytes());
        System.out.println(encodeString);
        ByteArrayOutputStream out = QRCode.from(encodeString).to(ImageType.PNG).stream();
        String baseimg = Base64.encodeBase64String(out.toByteArray());
        // 将base64编码的字符串直接作为img标签的src值即可（以<img src="data:image/jpeg;base64,开头）显示二维码 
        System.out.println(baseimg);
        
        String times = ObjectUtils.toString(new Date().getTime()/1000);
        System.out.println(times);
        System.out.println(Arrays.toString(times.getBytes()));
        //printHexString(times.getBytes())
        System.out.println(Long.toHexString(new Date().getTime()/1000));
        */
    	genQrCode("1234567", "D:\\", "test.png", "png");
    }  
    
    public static void printHexString( byte[] b) {     
	   for (int i = 0; i < b.length; i++) {    
	     String hex = Integer.toHexString(b[i] & 0xFF);    
	     if (hex.length() == 1) {    
	       hex = '0' + hex;    
	     }    
	     System.out.print(hex.toUpperCase() );    
	   }    
	  
	}

} 
